package org.javaboy.nacos02.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

@RestController
public class CallHelloController {

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("/callHello")
    public String callHello() throws IOException {
        List<ServiceInstance> nacos01 = discoveryClient.getInstances("nacos01");
        ServiceInstance instance = nacos01.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        String url = "http://" + host + ":" + port + "/hello";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String s = br.readLine();
        br.close();
        return s;
    }
}
